// 归并排序递归实现
void MergeSort(int* a, int n)
{
	int* tmp = (int*)malloc(sizeof(int) * n);
	if (tmp == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	_MergeSort(a,0,n-1,tmp);

	free(tmp);
	tmp = NULL;
}
// 归并排序非递归实现
void MergeSortNonR(int* a, int n)
{
	int* tmp = (int*)malloc(sizeof(int) * n);
	if (tmp == NULL)
	{
		perror("malloc");
		exit(-1);
	}

	// 归并每组数据个数，从1开始，因为1个认为是有序的，可以直接归并
	int rangeN = 1;
	while (rangeN < n)
	{
		for (int j = 0;j < n;j += 2 * rangeN)
		{
			int begin1 = j; int end1 = j+ rangeN -1;
			int begin2 = j+ rangeN, end2 = j + 2 * rangeN - 1;

			if (end1 > n)//end1越界  begin2 和 end2 肯定越界
			{
				break;
			}
			else if (begin2 > n)//begin2 越界  end2 肯定越界
			{
				break;
			}
			else if (end2 > n)
			{
				end2 = n - 1;
			}

			int i = j;
			while (begin1 <= end1 && begin2 <= end2)
			{
				if (a[begin1] <= a[begin2])
				{
					tmp[i++] = a[begin1++];
				}
				else
				{
					tmp[i++] = a[begin2++];
				}
			}
			while (begin1 <= end1)
			{
				tmp[i++] = a[begin1++];
			}

			while (begin2 <= end2)
			{
				tmp[i++] = a[begin2++];
			}
			// 归并一部分，拷贝一部分
			memcpy(a + j, tmp + j, sizeof(int) * (end2 - j + 1));
		
		}
		rangeN *= 2;
	}

	free(tmp);
	tmp = NULL;
}